package com.dlc.yunguang.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.widget.TextView;
import android.widget.Toast;
import butterknife.BindView;
import com.dlc.commonlibrary.dialog.WaitingDialog;
import com.dlc.commonlibrary.dialog.WelcomeDialog;
import com.dlc.commonlibrary.utils.DeviceUuidFactory;
import com.dlc.commonlibrary.utils.LogPlus;
import com.dlc.commonlibrary.utils.PrefUtil;
import com.dlc.yunguang.base.BaseActivity;
import com.dlc.yunguang.base.Constants;
import com.dlc.yunguang.helper.UserHelper;
import com.dlc.yunguang.net.NetConstants;
import com.dlc.yunguang.net.bean.LoginBean;
import com.dlc.yunguang.net.bean.RegisterBean;
import com.dlc.yunguang.net.exception.ErrorMsgException;
import com.dlc.yunguang.net.protocol.UserProto;
import com.dlc.yunguang.R;
import com.trello.rxlifecycle.android.ActivityEvent;
import java.util.UUID;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by kawaimisashi on 2017/7/20 0020.
 */

public class WeComeActivity extends BaseActivity
    implements ActivityCompat.OnRequestPermissionsResultCallback {

    @BindView(R.id.mac)
    TextView mMac;
    private WaitingDialog mDialog;
    private String tmDevice, tmSerial, tmPhone, androidId, uniqueId;
    public final static int REQUEST_READ_PHONE_STATE = 1;

    @Override
    protected int getLayoutID() {
        return R.layout.activity_wecome;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        int permissionCheck =
            ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE);

        if (permissionCheck != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                new String[] { Manifest.permission.READ_PHONE_STATE }, REQUEST_READ_PHONE_STATE);
        } else {
            getMachineCode();
        }

        //startActivity(QueryDataActivity.class);

    }

    private void login(final String username, final String password) {

        showWaitingDialog(R.string.login_ing, false);

        UserProto.get()
            .login(username, password, null)
            .subscribeOn(Schedulers.io())
            .compose(this.<LoginBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<LoginBean>() {
                @Override
                public void onCompleted() {
                    dismissWaitingDialog();
                }

                @Override
                public void onError(Throwable e) {
                    dismissWaitingDialog();

                    showOneToast(e.getMessage());
                    startActivity(LoginActivity.class);
                    finish();
                }

                @Override
                public void onNext(LoginBean loginBean) {
                    PrefUtil.getDefault()
                        .edit()
                        .putString(Constants.LoginData.PHONE, username)
                        .apply();
                    PrefUtil.getDefault()
                        .edit()
                        .putString(Constants.LoginData.PW, password)
                        .apply();
                    UserHelper.get().saveUserInfo(loginBean);
                    startActivity(MainActivity.class);
                    finish();
                }
            });
    }

    private void getMachineCode() {
        DeviceUuidFactory deviceUuidFactory = new DeviceUuidFactory(this);
        UUID deviceUuid = deviceUuidFactory.getDeviceUuid();
        uniqueId = deviceUuid.toString();
        uniqueId = uniqueId.replaceAll("-", "");
        uniqueId = uniqueId.substring(0,uniqueId.length()-8);
        mMac.setText("机器码="+uniqueId);
        LogPlus.e("机器码" + uniqueId);
        PrefUtil.getDefault().edit().putString(Constants.PHONE_NUMBER, uniqueId).apply();
      //  register();

        String phone = PrefUtil.getDefault().getString(Constants.LoginData.PHONE, "");
        String password = PrefUtil.getDefault().getString(Constants.LoginData.PW, "");
        login(phone, password);


    }

    private void register() {
        //showWaitingDialog("正在查看是否注册", false);
        UserProto.get()
            .register(uniqueId, null)
            .subscribeOn(Schedulers.io())
            .compose(this.<RegisterBean>bindUntilEvent(ActivityEvent.DESTROY))
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<RegisterBean>() {
                @Override
                public void onCompleted() {
                    //dismissWaitingDialog();
                }

                @Override
                public void onError(Throwable e) {
                    // dismissWaitingDialog();
                    ErrorMsgException errorMsgException = (ErrorMsgException) e;
                    showOneToast(e.getMessage());
                    if (errorMsgException.getCode() != NetConstants.CODE_NET_ERROR) {
                        WelcomeDialog dialog =
                            new WelcomeDialog(WeComeActivity.this, "请管理员审核你的手机注册码" + uniqueId,
                                true);

                        dialog.setOnCallBackListener(new WelcomeDialog.OnCallBack() {
                            @Override
                            public void sure() {
                                finish();
                            }
                        });
                    } else {
                        Toast.makeText(WeComeActivity.this, "请联网登陆", Toast.LENGTH_LONG).show();
                    }
                }

                @Override
                public void onNext(RegisterBean loginBean) {
                    //showToast(loginBean.msg);
                    String phone = PrefUtil.getDefault().getString(Constants.LoginData.PHONE, "");
                    String password = PrefUtil.getDefault().getString(Constants.LoginData.PW, "");
                    login(phone, password);
                }
            });
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions,
        @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_READ_PHONE_STATE:
                if ((grantResults.length > 0) && (grantResults[0]
                    == PackageManager.PERMISSION_GRANTED)) {
                    //TODO
                    getMachineCode();
                }
                break;
        }
    }
}
